<template>
  <a-upload
    name="file"
    :action="uploadAction"
    class="avatar-uploader"
    accept=".jpg,.png"
    :headers="headers"
    :showUploadList="false"
    listType="picture-card"
    :data="{'isup':1,'bizPath':bizPath}"
    :beforeUpload="beforeUpload"
    @change="handleChange">
    <img v-if="fileImg" style="width:90px;" :src="fileImg" alt="avatar" />
    <div v-else>
      <a-icon :type="loading ? 'loading' : 'plus'" />
      <div class="ant-upload-text">Upload</div>
    </div>
  </a-upload>
</template>

<script>

  import Vue from 'vue'
  import { ACCESS_TOKEN } from "@/store/mutation-types"

  const FILE_TYPE_ALL = "all"
  const FILE_TYPE_IMG = "image"
  const FILE_TYPE_TXT = "file"
  const uidGenerator=()=>{
    return '-'+parseInt(Math.random()*10000+1,10);
  }
  const getFileName=(path)=>{
    if(path.lastIndexOf("\\")>=0){
      let reg=new RegExp("\\\\","g");
      path = path.replace(reg,"/");
    }
    return path.substring(path.lastIndexOf("/")+1);
  }
  export default {
    name: 'JUploadOneImg',
    data(){
      return {
        uploadAction:window._CONFIG['domianURL']+"/sys/common/upload",
        // urlDownload:window._CONFIG['domianURL'] + "/sys/common/download/",
        // uploadAction:"",
        urlDownload:"",
        headers:{},
        fileList: [],
        loading: false,
        fileImg:""
      }
    },
    props:{
      text:{
        type:String,
        required:false,
        default:"点击上传"
      },
      fileType:{
        type:String,
        required:false,
        default:FILE_TYPE_ALL
      },
      /*这个属性用于控制文件上传的业务路径*/
      bizPath:{
        type:String,
        required:false,
        default:"temp"
      },
      value:{
        type:[String,Array],
        required:false
      },
      // update-begin- --- author:wangshuai ------ date:20190929 ---- for:Jupload组件增加是否能够点击
      disabled:{
        type:Boolean,
        required:false,
        default: false
      },
      // update-end- --- author:wangshuai ------ date:20190929 ---- for:Jupload组件增加是否能够点击
      //此属性被废弃了
      triggerChange:{
        type: Boolean,
        required: false,
        default: false
      },
    },
    watch:{
      value(val){
        var arr = val.split(',');
        if(arr.length>1){
          this.value = arr[1];
        }else{
          this.value = arr[0];
        }
        this.fileImg = this.value;
        if (val instanceof Array) {
          this.initFileList(val.join(','))
        } else {
          this.initFileList(val)
        }
      },
      fileList(val){
        if(val.length == 1){
          this.disabled = true;
        }
        if(val.length<1){
          this.disabled = false;
        }
      }
    },
    created(){
      if (this.value instanceof Array) {
        this.initFileList(this.value.join(','))
      } else {
        this.initFileList(this.value)
      }
      const token = Vue.ls.get(ACCESS_TOKEN);
      this.headers = {"X-Access-Token":token}
    },
    mounted(){
    },
    methods:{
      getBase64(img, callback) {
        const reader = new FileReader();
        reader.addEventListener('load', () => callback(reader.result));
        reader.readAsDataURL(img);
      },
      imgPreview(e){ 
        // var win = window.open();
        // var pdf = e.thumbUrl;
        // win.document.write('&lt;iframe src="' + pdf + '" frameborder="0" style="border:0; top:0px; left:0px; bottom:0px; right:0px; width:100%; height:100%;" allowfullscreen&gt;&lt;/iframe&gt;')
        window.open(e.url);
        
      },
      initFileList(paths){
        var that = this;
        if(!paths || paths.length==0){
          //return [];
          // update-begin- --- author:os_chengtgen ------ date:20190729 ---- for:issues:326,Jupload组件初始化bug
          that.fileList = [];
          return;
          // update-end- --- author:os_chengtgen ------ date:20190729 ---- for:issues:326,Jupload组件初始化bug
        }
        let fileList = [];
        let arr = paths.split(",")
        for(var a=0;a<arr.length;a++){
          fileList.push({
            uid:uidGenerator(),
            name:getFileName(arr[a]),
            status: 'done',
            url: that.urlDownload+arr[a],
            thumbUrl:that.urlDownload+arr[a],
            response:{
              status:"history",
              message:arr[a]
            }
          })
        }
        that.fileList = fileList;
        console.log(fileList)
      },
      handlePathChange(){
        let uploadFiles = this.fileList;
        this.fileImg = uploadFiles[0].url;
        this.$emit('change', uploadFiles[0].url);
      },
      beforeUpload(file){
        var fileType = file.type;
        if(fileType===FILE_TYPE_IMG){
          if(fileType.indexOf('image')<0){
            this.$message.warning('请上传图片');
            return false;
          }
        }else if(fileType===FILE_TYPE_TXT){
          if(fileType.indexOf('image')>=0){
            this.$message.warning('请上传文件');
            return false;
          }
        }
        if(file.size/1024/1024>2){
          this.$message.warning('文件大小不能大于2M');
          return false;
        }
        //TODO 扩展功能验证文件大小
        return true
      },
      handleChange(info) {
        let fileList = info.fileList;
        // if(fileList[0].size/1024>100){
        //   this.$message.warning('文件大小不能大于2M');
        //   return false;
        // }
        if (info.file.status === 'uploading') {
          this.loading = true;
          return;
        }
        if(info.file.status==='done'){
          this.getBase64(info.file.originFileObj, imageUrl => {
            this.fileList[0].thumbUrl = imageUrl;
            this.loading = false;
          });
          if(info.file.response.success){
            fileList = fileList.map((file) => {
              if (file.response) {
                file.url = this.urlDownload+file.response.message;
              }
              return file;
            });
          }
          this.$message.success(`${info.file.name} 上传成功!`);
        }else if (info.file.status === 'error') {
          this.$message.error(`${info.file.name} 上传失败.`);
        }else if(info.file.status === 'removed'){
          this.handleDelete(info.file)
        }
        this.fileList = fileList
        if(info.file.status==='done' || info.file.status === 'removed'){
          this.handlePathChange()
        }
      },
      handleDelete(file){
        //如有需要新增 删除逻辑
        console.log(file)
      },
    },
    model: {
      prop: 'value',
      event: 'change'
    }
  }
</script>

<style scoped>
  .avatar-uploader > .ant-upload {
    width: 128px;
    height: 128px;
  }
  .ant-upload-select-picture-card i {
    font-size: 32px;
    color: #999;
  }

  .ant-upload-select-picture-card .ant-upload-text {
    margin-top: 8px;
    color: #666;
  }
</style>